<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>Spring 事务实现 | flyingzc's blog</title><meta name="author" content="flyingzc"><meta name="copyright" content="flyingzc"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="Spring 事务实现Spring 事务使用123456789101112131415161718192021222324@Transactional注解配置项    事务传播行为        PROPAGATION_REQUIRED            当前方法必须在事务中，没有就创建，有就加入。        PROPAGATION_SUPPORTS            有事务就加入，没">
<meta property="og:type" content="article">
<meta property="og:title" content="Spring 事务实现">
<meta property="og:url" content="https://flyingzc.github.io/articles/spring/spring03-transaction.html">
<meta property="og:site_name" content="flyingzc&#39;s blog">
<meta property="og:description" content="Spring 事务实现Spring 事务使用123456789101112131415161718192021222324@Transactional注解配置项    事务传播行为        PROPAGATION_REQUIRED            当前方法必须在事务中，没有就创建，有就加入。        PROPAGATION_SUPPORTS            有事务就加入，没">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://flyingzc.github.io/images/zc-icon.jpeg">
<meta property="article:published_time" content="2023-12-27T16:00:00.000Z">
<meta property="article:modified_time" content="2025-01-21T01:51:41.214Z">
<meta property="article:author" content="flyingzc">
<meta property="article:tag" content="Spring">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://flyingzc.github.io/images/zc-icon.jpeg"><script type="application/ld+json">{
  "@context": "https://schema.org",
  "@type": "BlogPosting",
  "headline": "Spring 事务实现",
  "url": "https://flyingzc.github.io/articles/spring/spring03-transaction.html",
  "image": "https://flyingzc.github.io/images/zc-icon.jpeg",
  "datePublished": "2023-12-27T16:00:00.000Z",
  "dateModified": "2025-01-21T01:51:41.214Z",
  "author": [
    {
      "@type": "Person",
      "name": "flyingzc",
      "url": "https://flyingzc.github.io/"
    }
  ]
}</script><link rel="shortcut icon" href="/images/zc-icon.jpeg"><link rel="canonical" href="https://flyingzc.github.io/articles/spring/spring03-transaction.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><meta name="google-site-verification" content="DentpX3LnP_WNgEeFnNIcTZZky-Bby-zL-uI_9GqTAw"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css"><script>
    (() => {
      
    const saveToLocal = {
      set: (key, value, ttl) => {
        if (!ttl) return
        const expiry = Date.now() + ttl * 86400000
        localStorage.setItem(key, JSON.stringify({ value, expiry }))
      },
      get: key => {
        const itemStr = localStorage.getItem(key)
        if (!itemStr) return undefined
        const { value, expiry } = JSON.parse(itemStr)
        if (Date.now() > expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return value
      }
    }

    window.btf = {
      saveToLocal,
      getScript: (url, attr = {}) => new Promise((resolve, reject) => {
        const script = document.createElement('script')
        script.src = url
        script.async = true
        Object.entries(attr).forEach(([key, val]) => script.setAttribute(key, val))
        script.onload = script.onreadystatechange = () => {
          if (!script.readyState || /loaded|complete/.test(script.readyState)) resolve()
        }
        script.onerror = reject
        document.head.appendChild(script)
      }),
      getCSS: (url, id) => new Promise((resolve, reject) => {
        const link = document.createElement('link')
        link.rel = 'stylesheet'
        link.href = url
        if (id) link.id = id
        link.onload = link.onreadystatechange = () => {
          if (!link.readyState || /loaded|complete/.test(link.readyState)) resolve()
        }
        link.onerror = reject
        document.head.appendChild(link)
      }),
      addGlobalFn: (key, fn, name = false, parent = window) => {
        if (!false && key.startsWith('pjax')) return
        const globalFn = parent.globalFn || {}
        globalFn[key] = globalFn[key] || {}
        globalFn[key][name || Object.keys(globalFn[key]).length] = fn
        parent.globalFn = globalFn
      }
    }
  
      
      const activateDarkMode = () => {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      const activateLightMode = () => {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }

      btf.activateDarkMode = activateDarkMode
      btf.activateLightMode = activateLightMode

      const theme = saveToLocal.get('theme')
    
          theme === 'dark' ? activateDarkMode() : theme === 'light' ? activateLightMode() : null
        
      
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        document.documentElement.classList.toggle('hide-aside', asideStatus === 'hide')
      }
    
      
    const detectApple = () => {
      if (/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)) {
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
  
    })()
  </script><script async="async" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><script>(adsbygoogle = window.adsbygoogle || []).push({
  google_ad_client: '',
  enable_page_level_ads: 'true'
});</script><script>const GLOBAL_CONFIG = {
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  highlight: {"plugin":"highlight.js","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false,"highlightFullpage":false,"highlightMacStyle":false},
  copy: {
    success: '复制成功',
    error: '复制失败',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'null',
  Snackbar: undefined,
  infinitegrid: {
    js: 'https://cdn.jsdelivr.net/npm/@egjs/infinitegrid/dist/infinitegrid.min.js',
    buttonText: '加载更多'
  },
  isPhotoFigcaption: false,
  islazyloadPlugin: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Spring 事务实现',
  isHighlightShrink: false,
  isToc: true,
  pageType: 'post'
}</script><link rel="stylesheet" href="/self/github-dark.css"><meta name="generator" content="Hexo 7.0.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img text-center"><img src="/images/zc-icon.jpeg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data text-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">84</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">36</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">29</div></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header"><nav id="nav"><span id="blog-info"><a class="nav-site-title" href="/"><span class="site-name">flyingzc's blog</span></a><a class="nav-page-title" href="/"><span class="site-name">Spring 事务实现</span></a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div></div><div id="toggle-menu"><span class="site-page"><i class="fas fa-bars fa-fw"></i></span></div></div></nav><div id="post-info"><h1 class="post-title">Spring 事务实现</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2023-12-27T16:00:00.000Z" title="发表于 2023-12-28 00:00:00">2023-12-28</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2025-01-21T01:51:41.214Z" title="更新于 2025-01-21 09:51:41">2025-01-21</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Spring/">Spring</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title=""><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">浏览量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="container post-content" id="article-container"><h1 id="Spring-事务实现"><a href="#Spring-事务实现" class="headerlink" title="Spring 事务实现"></a>Spring 事务实现</h1><h2 id="Spring-事务使用"><a href="#Spring-事务使用" class="headerlink" title="Spring 事务使用"></a>Spring 事务使用</h2><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><code class="hljs km">@Transactional注解配置项<br>    事务传播行为<br>        PROPAGATION_REQUIRED<br>            当前方法必须在事务中，没有就创建，有就加入。<br>        PROPAGATION_SUPPORTS<br>            有事务就加入，没有就以非事务方式执行。<br>        PROPAGATION_MANDATORY<br>            有事务就加入，没有就抛出异常。<br>        PROPAGATION_REQUIRES_NEW<br>            永远创建新事务执行，之前若有事务则挂起之前的事务。<br>        PROPAGATION_NOT_SUPPORTED<br>            以非事务方式执行。之前若有事务则挂起之前的事务。<br>        PROPAGATION_NEVER<br>            以非事务方式执行。之前若有事务则抛出异常。<br>        PROPAGATION_NESTED<br>            当前若有事务，则在嵌套事务内执行。如果当前没有事务,则按 REQUIRED 属性执行。<br>    事务隔离级别<br>    readOnly设置<br>    超时时间<br>    异常回滚设置<br>        rollbackFor<br>        rollbackForClassName<br>        noRollbackFor<br>        noRollbackForClassName<br></code></pre></td></tr></table></figure>

<h2 id="Spring-事务实现-1"><a href="#Spring-事务实现-1" class="headerlink" title="Spring 事务实现"></a>Spring 事务实现</h2><h3 id="相关类"><a href="#相关类" class="headerlink" title="相关类"></a>相关类</h3><h3 id="总体流程"><a href="#总体流程" class="headerlink" title="总体流程"></a>总体流程</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><code class="hljs km">启动阶段<br>    创建代理对象(参见AOP逻辑)<br>        获取切面列表<br>        创建aop代理对象<br>事务执行<br>    获取事务属性<br>    获取事务管理器，创建事务<br>        创建物理连接<br>        autoCommit等连接属性设置<br>        物理连接和当前线程绑定<br>    调用目标方法，执行业务逻辑<br>    回滚/提交事务<br>        前置处理<br>        物理连接执行rollback/commit操作<br>        后置处理<br>        后置清理<br>            清理threadLocal<br>            重置autoCommit<br>            关闭连接<br>            重置 connectionHolder<br></code></pre></td></tr></table></figure>

<h3 id="启动阶段创建代理对象逻辑"><a href="#启动阶段创建代理对象逻辑" class="headerlink" title="启动阶段创建代理对象逻辑"></a>启动阶段创建代理对象逻辑</h3><p>参考之前写的 Spring AOP 实现。<br><a target="_blank" rel="noopener" href="https://blog.csdn.net/kaishizhangcheng/article/details/100127591">启动阶段创建代理对象逻辑</a></p>
<h3 id="执行阶段调用链路"><a href="#执行阶段调用链路" class="headerlink" title="执行阶段调用链路"></a>执行阶段调用链路</h3><p>事务执行阶段，会通过启动阶段生成的代理类调用目标方法，在此之前通过 TransactionAspectSupport 处理自动开启事务&#x2F;提交事务等逻辑。调用链路如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br></pre></td><td class="code"><pre><code class="hljs km">aop.framework.CglibAopProxy.CglibMethodInvocation#proceed <br>事务处理流程<br>    aop.framework.ReflectiveMethodInvocation#proceed<br>        transaction.interceptor.TransactionInterceptor#invoke<br>        事务拦截器处理<br>            transaction.interceptor.TransactionAspectSupport#invokeWithinTransaction <br>            事务内调用目标方法<br>                transaction.interceptor.TransactionAspectSupport#getTransactionAttributeSource<br>                transaction.interceptor.AbstractFallbackTransactionAttributeSource#getTransactionAttribute<br>                获取 transactionAttribute<br>                transaction.interceptor.TransactionAspectSupport#determineTransactionManager <br>                获取事务管理器<br>                    transaction.interceptor.DefaultTransactionAttribute#getQualifier<br>                    transaction.interceptor.TransactionAspectSupport#getTransactionManager<br>                    util.ConcurrentReferenceHashMap#get<br>                    缓存获取 tm<br>                    beans.factory.support.DefaultListableBeanFactory#getBean <br>                    缓存没有,则通过 beanFactory 获取事务管理器 bean<br>                    util.ConcurrentReferenceHashMap#putIfAbsent <br>                    缓存事务管理器<br>                transaction.interceptor.TransactionAspectSupport#asPlatformTransactionManager <br>                将 tm 转成 PlatformTransactionManager 类型<br>                transaction.interceptor.TransactionAspectSupport#methodIdentification <br>                获取方法名标识<br>                    transaction.interceptor.TransactionAspectSupport#methodIdentification<br>                    transaction.interceptor.DefaultTransactionAttribute#getDescriptor<br>                transaction.interceptor.TransactionAspectSupport#createTransactionIfNecessary <br>                创建事务<br>                    transaction.support.DefaultTransactionDefinition#getName<br>                    transaction.support.AbstractPlatformTransactionManager#getTransaction <br>                    通过 tm 获取事务<br>                        jdbc.datasource.DataSourceTransactionManager#doGetTransaction <br>                        创建 DataSourceTransactionObject 对象<br>                            jdbc.datasource.JdbcTransactionObjectSupport#setSavepointAllowed<br>                            jdbc.datasource.DataSourceTransactionManager#obtainDataSource <br>                            获取 dataSource<br>                            transaction.support.TransactionSynchronizationManager#getResource<br>                            jdbc.datasource.DataSourceTransactionManager.DataSourceTransactionObject#setConnectionHolder<br>                        jdbc.datasource.DataSourceTransactionManager#isExistingTransaction <br>                        通过判断 connectionHolder 是否为空判断是否在事务中<br>                            jdbc.datasource.JdbcTransactionObjectSupport#hasConnectionHolder<br>                        transaction.support.DelegatingTransactionDefinition#getTimeout<br>                        获取超时时间<br>                        transaction.support.DelegatingTransactionDefinition#getPropagationBehavior<br>                        获取传播属性<br>                        transaction.support.AbstractPlatformTransactionManager#suspend <br>                        当前如果有事务挂起事务，根据传播行为决定<br>                            transaction.support.TransactionSynchronizationManager#isSynchronizationActive<br>                        transaction.support.AbstractPlatformTransactionManager#startTransaction <br>                        开启事务<br>                            transaction.support.AbstractPlatformTransactionManager#getTransactionSynchronization<br>                            transaction.support.AbstractPlatformTransactionManager#newTransactionStatus <br>                            创建 DefaultTransactionStatus<br>                            jdbc.datasource.DataSourceTransactionManager#doBegin <br>                            开启事务<br>                                jdbc.datasource.JdbcTransactionObjectSupport#hasConnectionHolder<br>                                jdbc.datasource.DataSourceTransactionManager#obtainDataSource <br>                                获取 dataSource,创建 connection<br>                                jdbc.datasource.DataSourceTransactionManager.DataSourceTransactionObject#setConnectionHolder <br>                                将 connection 包成 holder 塞到 DataSourceTransactionObject 里<br>                                    jdbc.datasource.JdbcTransactionObjectSupport#setConnectionHolder<br>                                transaction.support.ResourceHolderSupport#setSynchronizedWithTransaction<br>                                jdbc.datasource.ConnectionHolder#getConnection<br>                                jdbc.datasource.DataSourceUtils#prepareConnectionForTransaction <br>                                连接做准备工作，比如是否要设置 readonly,隔离级别<br>                                jdbc.datasource.JdbcTransactionObjectSupport#setPreviousIsolationLevel 塞值<br>                                jdbc.datasource.JdbcTransactionObjectSupport#setReadOnly 塞值<br>                                com.mysql.cj.jdbc.ConnectionImpl#getAutoCommit <br>                                如果物理连接是自动提交 autoCommit=true<br>                                jdbc.datasource.DataSourceTransactionManager.DataSourceTransactionObject#setMustRestoreAutoCommit <br>                                设置DataSourceTransactionObject属性，后面需要恢复autoCommit值<br>                                com.mysql.cj.jdbc.ConnectionImpl#setAutoCommit <br>                                设置 autoCommit为false，非自动提交<br>                                jdbc.datasource.DataSourceTransactionManager#prepareTransactionalConnection<br>                                jdbc.datasource.ConnectionHolder#setTransactionActive <br>                                设置事务 active 状态<br>                                transaction.support.AbstractPlatformTransactionManager#determineTimeout <br>                                设置事务超时时间<br>                                transaction.support.TransactionSynchronizationManager#bindResource <br>                                将物理连接和当前线程绑定，threadLocal-&gt; map&lt;dataSource, connectionHolder&gt;<br>                            transaction.support.AbstractPlatformTransactionManager#prepareSynchronization <br>                            向TransactionSynchronizationManager里设置隔离级别，readonly等属性<br>                                transaction.support.DelegatingTransactionDefinition#getIsolationLevel<br>                                transaction.support.TransactionSynchronizationManager#setCurrentTransactionIsolationLevel <br>                                设置隔离级别<br>                                transaction.support.DelegatingTransactionDefinition#isReadOnly<br>                                transaction.support.TransactionSynchronizationManager#setCurrentTransactionReadOnly <br>                                设置 readonly<br>                                transaction.support.TransactionSynchronizationManager#setCurrentTransactionName<br>                                transaction.support.TransactionSynchronizationManager#initSynchronization<br>                    transaction.interceptor.TransactionAspectSupport#prepareTransactionInfo <br>                    将 transactionInfo 和当前线程绑定<br>                        transaction.interceptor.TransactionAspectSupport.TransactionInfo#newTransactionStatus<br>                        transaction.interceptor.TransactionAspectSupport.TransactionInfo#bindToThread<br>                aop.framework.CglibAopProxy.CglibMethodInvocation#proceed <br>                调用目标方法<br>                    aop.framework.ReflectiveMethodInvocation#proceed<br>                        aop.framework.CglibAopProxy.CglibMethodInvocation#invokeJoinpoint<br>                            cglib.proxy.MethodProxy#invoke<br>                                com.zc.example.service.impl.OrderServiceImpl$$FastClassBySpringCGLIB$$a1c48f40#invoke<br>                                通过cglib代理类调用目标方法<br>                                    com.zc.example.service.impl.OrderServiceImpl#saveFailed<br>                                        transaction.interceptor.TransactionAspectSupport#completeTransactionAfterThrowing <br>                                        事务异常场景处理<br>                                            transaction.interceptor.TransactionAspectSupport.TransactionInfo#getTransactionStatus<br>                                            transaction.interceptor.DelegatingTransactionAttribute#rollbackOn <br>                                            判断异常是否需要回滚<br>                                                transaction.interceptor.RuleBasedTransactionAttribute#rollbackOn<br>                                            transaction.support.AbstractPlatformTransactionManager#rollback <br>                                            如果需要回滚，则执行回滚<br>                                                transaction.support.AbstractPlatformTransactionManager#processRollback <br>                                                处理回滚<br>                                                    transaction.support.AbstractPlatformTransactionManager#triggerBeforeCompletion <br>                                                    前置处理<br>                                                        transaction.support.DefaultTransactionStatus#isNewSynchronization<br>                                                        transaction.support.TransactionSynchronizationUtils#triggerBeforeCompletion<br>                                                            transaction.support.TransactionSynchronizationManager#getSynchronizations<br>                                                            transaction.support.TransactionSynchronizationManager#unbindResource<br>                                                            jdbc.datasource.DataSourceUtils#releaseConnection<br>                                                    jdbc.datasource.DataSourceTransactionManager#doRollback <br>                                                    执行回滚操作<br>                                                        transaction.support.DefaultTransactionStatus#getTransaction<br>                                                        jdbc.datasource.JdbcTransactionObjectSupport#getConnectionHolder<br>                                                        jdbc.datasource.ConnectionHolder#getConnection<br>                                                        获取物理连接，执行回滚操作<br>                                                            jdbc.datasource.SimpleConnectionHandle#getConnection <br>                                                            获取物理连接<br>                                                            con.rollback() <br>                                                            通过物理连接执行回滚<br>                                                    transaction.support.AbstractPlatformTransactionManager#triggerAfterCompletion <br>                                                    后置处理<br>                                                        transaction.support.TransactionSynchronizationManager#getSynchronizations<br>                                                        transaction.support.TransactionSynchronizationManager#clearSynchronization<br>                                                        transaction.support.AbstractPlatformTransactionManager#invokeAfterCompletion<br>                                                    transaction.support.AbstractPlatformTransactionManager#cleanupAfterCompletion <br>                                                    后置清理<br>                                                        transaction.support.AbstractTransactionStatus#setCompleted<br>                                                        transaction.support.TransactionSynchronizationManager#clear <br>                                                        清理TransactionSynchronizationManager里的threadLocal信息<br>                                                        jdbc.datasource.DataSourceTransactionManager#doCleanupAfterCompletion <br>                                                        执行后置清理<br>                                                            jdbc.datasource.DataSourceTransactionManager#obtainDataSource<br>                                                            transaction.support.TransactionSynchronizationManager#unbindResource <br>                                                            清理当前线程threadLocal绑定的dataSource<br>                                                            jdbc.datasource.JdbcTransactionObjectSupport#getConnectionHolder<br>                                                            jdbc.datasource.DataSourceTransactionManager.DataSourceTransactionObject#isMustRestoreAutoCommit <br>                                                            判断是否需要重置autoCommit值<br>                                                            con.setAutoCommit(true)<br>                                                            重置autoCommit<br>                                                            jdbc.datasource.DataSourceUtils#resetConnectionAfterTransaction <br>                                                            连接重置操作<br>                                                            jdbc.datasource.DataSourceUtils#releaseConnection <br>                                                            将连接关闭放回连接池<br>                                                                jdbc.datasource.DataSourceUtils#doReleaseConnection<br>                                                                    jdbc.datasource.DataSourceUtils#doCloseConnection<br>                                                            jdbc.datasource.ConnectionHolder#clear <br>                                                            清理txObject.connectionHolder里的信息<br>                                        transaction.interceptor.TransactionAspectSupport#cleanupTransactionInfo <br>                                        清理transactionInfoHolder<br>                                            transaction.interceptor.TransactionAspectSupport.TransactionInfo#restoreThreadLocalStatus<br></code></pre></td></tr></table></figure>
<link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/markmap-toolbar@0.18.10/dist/style.css"><script src="https://fastly.jsdelivr.net/npm/d3@7"></script><script src="https://fastly.jsdelivr.net/npm/markmap-view@0.18.10"></script><script src="https://fastly.jsdelivr.net/npm/markmap-toolbar@0.18.10"></script>
<link rel="stylesheet" href="/css/markmap.css">

<script src="/js/markmap.js"></script>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta"><i class="fas fa-circle-user fa-fw"></i>文章作者: </span><span class="post-copyright-info"><a href="https://flyingzc.github.io">flyingzc</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta"><i class="fas fa-square-arrow-up-right fa-fw"></i>文章链接: </span><span class="post-copyright-info"><a href="https://flyingzc.github.io/articles/spring/spring03-transaction.html">https://flyingzc.github.io/articles/spring/spring03-transaction.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta"><i class="fas fa-circle-exclamation fa-fw"></i>版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来源 <a href="https://flyingzc.github.io" target="_blank">flyingzc's blog</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Spring/">Spring</a></div><div class="post-share"><div class="social-share" data-image="/images/zc-icon.jpeg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><a class="pagination-related" href="/articles/spring/spring10-ConfigurationClassParser.html" title="Spring ConfigurationClassParser"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2020-06-13</div><div class="info-item-2">Spring ConfigurationClassParser</div></div><div class="info-2"><div class="info-item-1">Spring ConfigurationClassParser123456789101112131415161718192021- ConfigurationClassPostProcessor.processConfigBeanDefinitions()- 1.获取 registry 中的 beanDefinitionNames- 2.遍历beanDefinitionNames判断beanDefinition 是否是 @Configuration 配置类,若是则添加到 configCandidates 集合中- 3.configCandidates根据Order排序- 4.创建ConfigurationClassParser,配置类解析器- 5.遍历configCandidates,调用parser.parse()进行配置类解析    - ConfigurationClassParser.parse()    - 1.遍历configCandidates,获取当前的beanDefinition    -...</div></div></div></a></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info text-center"><div class="avatar-img"><img src="/images/zc-icon.jpeg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info-name">flyingzc</div><div class="author-info-description">不积跬步无以至千里<br/>不积小流无以成江海</div><div class="site-data"><a href="/archives/"><div class="headline">文章</div><div class="length-num">84</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">36</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">29</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/FlyingZC"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons"><a class="social-icon" href="https://github.com/FlyingZC" target="_blank" title="Github"><i class="fab fa-github" style="color: #24292e;"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">FlyingZC's Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#Spring-%E4%BA%8B%E5%8A%A1%E5%AE%9E%E7%8E%B0"><span class="toc-number">1.</span> <span class="toc-text">Spring 事务实现</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#Spring-%E4%BA%8B%E5%8A%A1%E4%BD%BF%E7%94%A8"><span class="toc-number">1.1.</span> <span class="toc-text">Spring 事务使用</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Spring-%E4%BA%8B%E5%8A%A1%E5%AE%9E%E7%8E%B0-1"><span class="toc-number">1.2.</span> <span class="toc-text">Spring 事务实现</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%9B%B8%E5%85%B3%E7%B1%BB"><span class="toc-number">1.2.1.</span> <span class="toc-text">相关类</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%80%BB%E4%BD%93%E6%B5%81%E7%A8%8B"><span class="toc-number">1.2.2.</span> <span class="toc-text">总体流程</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%90%AF%E5%8A%A8%E9%98%B6%E6%AE%B5%E5%88%9B%E5%BB%BA%E4%BB%A3%E7%90%86%E5%AF%B9%E8%B1%A1%E9%80%BB%E8%BE%91"><span class="toc-number">1.2.3.</span> <span class="toc-text">启动阶段创建代理对象逻辑</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%89%A7%E8%A1%8C%E9%98%B6%E6%AE%B5%E8%B0%83%E7%94%A8%E9%93%BE%E8%B7%AF"><span class="toc-number">1.2.4.</span> <span class="toc-text">执行阶段调用链路</span></a></li></ol></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/ignite/ignite03-transaction-begin.html" title="Apache Ignite 开启事务执行流程">Apache Ignite 开启事务执行流程</a><time datetime="2025-10-10T16:00:00.000Z" title="发表于 2025-10-11 00:00:00">2025-10-11</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/ignite/ignite02-transaction.html" title="Apache Ignite 分布式事务原理">Apache Ignite 分布式事务原理</a><time datetime="2025-09-17T16:00:00.000Z" title="发表于 2025-09-18 00:00:00">2025-09-18</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/ignite/ignite01-build.html" title="Apache Ignite IDEA 环境搭建">Apache Ignite IDEA 环境搭建</a><time datetime="2025-09-10T16:00:00.000Z" title="发表于 2025-09-11 00:00:00">2025-09-11</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/druid/druid01-resultset-leak.html" title="ShardingSphere JDBC 使用 Druid 连接池 ResultSet 内存泄露分析">ShardingSphere JDBC 使用 Druid 连接池 ResultSet 内存泄露分析</a><time datetime="2025-06-30T16:00:00.000Z" title="发表于 2025-07-01 00:00:00">2025-07-01</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/jmeter/jmeter01-shardingsphere.html" title="Jmeter 压测 ShardingSphere">Jmeter 压测 ShardingSphere</a><time datetime="2025-06-30T16:00:00.000Z" title="发表于 2025-07-01 00:00:00">2025-07-01</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2025 By flyingzc</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="日间和夜间模式切换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside-config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>